<template>
  <div class="center py-6px" ref="root">
    <van-loading
      :size="`${14 / 36}rem`"
      type="spinner"
      v-if="status === 'loading'"
    ></van-loading>
    <div class="text-size-12px color-[var(--van-text-color-2)] ml-6px">
      {{ text }}
    </div>
  </div>
</template>

<script setup lang="ts">
import type { LoadMoreStatus } from "@/enums/loadMore";

const props = withDefaults(
  defineProps<{
    status?: LoadMoreStatus;
    loadingText?: string;
    nomoreText?: string;
    loadmoreText?: string;
  }>(),
  {
    status: "nomore",
    loadingText: "loading...",
    nomoreText: "nomore",
    loadmoreText: "loadmore"
  }
);
const emits = defineEmits(["loadmore"]);
const text = computed(() => {
  const key = `${props.status}Text` as keyof typeof props;
  return props[key] || "";
});

const root = ref<HTMLElement | null>(null);
const observer = ref<IntersectionObserver | null>(null);

onMounted(() => {
  observer.value = new IntersectionObserver(
    entries => {
      if (entries[0].isIntersecting) {
        emits("loadmore");
      }
    },
    {
      root: null,
      threshold: 0.1
    }
  );
  unref(observer)?.observe(unref(root)!);
});

onBeforeUnmount(() => {
  unref(observer)?.disconnect();
});

defineExpose({
  root
});
</script>
